﻿$(function () {
    var $datagrid = $("#datagrid"), $toolbar = $("#toolbar"), $dialog = $("#dialog");
    $("#saveTicket").on("click", function () {
        openDialog();
    });
    $("#editTicket").on("click", function () {
        var rows = $datagrid.datagrid('getSelected');
        if (rows) {
            var targetId = rows.Id;
            openDialog("form-edit.jsp?targetId=" + targetId);
        } else {
            Constant.showMessage("请选择目标");
        }
    });


    function updateAccount() {
        $("form").form("submit", {
            url: $("#ff").attr("action"),
            onSubmit: function () {
                KindEditor.sync('textarea[name="description"]');
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                }
                return isValid;
            },
            success: function (respText) {
                var resp = $.parseJSON(respText);
                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                if (resp.ReturnCode == 1) {
                    uploading(resp.DataList.Data.Id);
                    uploadings(resp.DataList.Data.Id);
                    $dialog.dialog("close");
                    $("#datagrid").datagrid("reload");
                    var checkNumber = 0;
                    var checkQuery = function () {
                        setTimeout(function () {
                            if (postImgNumber == selectImgNumber) {
                                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                            } else {
                                if (checkNumber == 5) {
                                    Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                                } else {
                                    checkQuery();
                                }
                            }
                            checkNumber += 1;
                        }, 500);
                    }
                    checkQuery();
                }
            }
        });
    }

    function saveAccount() {
        $("form").form("submit", {
            url: $("#ff").attr("action"),
            onSubmit: function () {
                KindEditor.sync('textarea[name="description"]');
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                }
                return isValid;
            },
            success: function (respText) {
                var resp = $.parseJSON(respText);
                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                if (resp.ReturnCode == 1) {
                    uploading(resp.DataList.Data.Id);
                    uploadings(resp.DataList.Data.Id);
                    $dialog.dialog("close");
                    $("#datagrid").datagrid("reload");
                    var checkNumber = 0;
                    var checkQuery = function () {
                        setTimeout(function () {
                            if (postImgNumber == selectImgNumber) {
                                Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                            } else {
                                if (checkNumber == 5) {
                                    Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                                } else {
                                    checkQuery();
                                }
                            }
                            checkNumber += 1;
                        }, 500);
                    }
                    checkQuery();
                    $("#visaChild").dialog('close');
                }
            }
        });
    }

    function openDialog(editPath) {
        $dialog.dialog({
            title: editPath ? "编辑内容" : "新增内容",
            width: 500,
            height: 500,
            closed: false,
            cache: false,
            href: editPath || 'form.jsp',
            modal: true,
            onClose: function () {

            },
            buttons: [{
                text: '保存',
                handler: editPath ? updateAccount : saveAccount
            }]
        });
    }

    $datagrid.datagrid({
        singleSelect: true,
        fit: true,
        border: false,
        fitColumns: true,
        url: Constant.ctx("/mulanweb/admin/visa/search"),
        method: 'post',
        pagination: true,
        toolbar: $toolbar,
        columns: [[
            {field: 'Id', title: '编号'},
            {field: 'Title', title: '标题'},
            {field: 'Country', title: '国家'},
            {field: 'CreateTime', title: '创建时间'},
            {field: 'UpdateTime', title: '最后更新时间'},
            {
                field: 'StatusId', title: '状态', formatter: function (v, r, i) {
                var html = '';
                if (v == 20) {
                    return '  <a href="#" onclick="lowerStatus(' + r.Id + ')">出售中,点击下架</a>';
                } else if (v == 21) {
                    return '  <a href="#" onclick="upperStatus(' + r.Id + ')">已下架，点击上架</a>';
                } else {
                    return v;
                }
            }
            },
            {
                field: 'DeleteTime', title: '操作', formatter: function (v, r, i) {
                if (!v) {
                    return '  <a href="#" onclick="deleteVisa(' + r.Id + ')">删除</a>'
                }
                return v;
            }
            }
        ]],
        onBeforeLoad: function (param) {
            param.PageNumber = param.page;
            param.PageSize = param.rows;

            var country = $("#country").val();
            if (country) {
                param.country = country;
            }
            var title = $("#title").val();
            if (title) {
                param.title = title;
            }

            return true;
        },
        loadFilter: function (data) {
            var newData = {};
            if (data.ReturnCode == 1) {
                newData.rows = data.DataList;
                if (newData.rows.length > 0) {
                    newData.total = data.TotalRow;
                } else {
                    newData.total = 0;
                }
            }
            return newData;
        },
        onDblClickRow: function (index, rows) {
            showDetail(rows);
        }
    });
    function showDetail(row) {
        $.post(Constant.ctx("/mulanweb/admin/visa/getVisaDetail"), {visaId: row.Id}, function (info) {
            var html = '<h3>子产品介绍：</h3>';
            $.post(Constant.ctx("/mulanweb/admin/visa/getVisaChild"), {visaId: row.Id}, function (visaChilds) {
                var childHtml = '<div style="width:100%"><div id="childHtml">';
                for (var child in visaChilds.DataList) {

                    childHtml = childHtml +
                        '<button type="button" class="btn btn-info" style="width:25%; margin:10px" ' +
                        'onclick="addVisaChild(\'' + row.Id + '\',\'' + visaChilds.DataList[child].Id + '\')">' +
                        visaChilds.DataList[child].Name + '</button>';

                }
                childHtml = childHtml + '</div><button type="button" class="btn btn-primary" style="width:25%;" onclick="addVisaChild(\'' + row.Id + '\')">+添加+</button>'
                    + '</div>';
                html = html + childHtml;
                html = html + '<h3>详情介绍：</h3>';
                html = html + info.DataList.Description;
                $("#dialogDetail").html(html);
            })
        })
        $("#dialogDetail").dialog({
            title: '详情',
            width: 300,
            height: 450,
            inline: true,
        });
    }


    var postImgNumber = 0;
    var selectImgNumber = 0;
    //保存主图
    function uploading(ticketId) {
        var files = document.getElementById('logoImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/save?targetId=' + ticketId + '&typeId=18'), "false");//typeId=13表示为门票券票logo图片
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
        return true;
    }

    //保存轮播图
    function uploadings(ticketId) {
        var files = document.getElementById('fileImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=17'), 'false');//typeId=13表示为门票券票图片
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
    }

    //更新主图
    function uploading2(ticketId) {
        var files = document.getElementById('detail-logoImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=18'), "false");//typeId=14表示为门票券票logo图片
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
    }

    //更新轮播图
    function uploadings2(ticketId) {
        var files = document.getElementById('detail-fileImage').files;
        selectImgNumber = selectImgNumber + files.length;
        for (var i = 0; i < files.length; i++) {
            var fd = new FormData();
            fd.append('fileToUpload', files[i]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function () {
            }, false);
            xhr.addEventListener('load', function () {
            }, false);
            xhr.addEventListener('error', function () {
            }, false);
            xhr.addEventListener('abort', function () {
            }, false);
            xhr.open('POST', Constant.ctx('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=17'), "false");
            //xhr.open('POST', Constant.toAbsoluteURL('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=13'));//typeId=13表示为门票券票图片
            /* * 如仍 出现 遗漏提交的问题，则使用如下方式同步提交
             xhr.open('POST', Constant.toAbsoluteURL('/mulanweb/admin/photo/update?targetId=' + ticketId + '&typeId=13'),"async=false||true");//typeId=13表示为门票券票图片*/
            xhr.send(fd);
            postImgNumber = postImgNumber + 1;
        }
    }
});
function doSearch() {
    $("#datagrid").datagrid("reload");
}
function deleteVisa(visaId) {
    $.messager.confirm('警告', '您确定删除此内容?', function (r) {
        if (r) {
            var url = Constant.ctx("/mulanweb/admin/visa/delete");
            $.post(url, {visaId: visaId}, function (info) {
                if (info.ReturnCode == 1) {
                    Constant.showMessage(info.AlertMessage, "操作成功");
                    $("#datagrid").datagrid("reload");
                } else {
                    Constant.showMessage(info.message, "操作失败");
                }
            })
        }
    });
}

function lowerStatus(visaId){
    var url = Constant.ctx("/mulanweb/admin/visa/lowerStatus");
    $.post(url, {visaId: visaId}, function (info) {
        if (info.ReturnCode == 1) {
            Constant.showMessage(info.AlertMessage, "操作成功");
            $("#datagrid").datagrid("reload");
        } else {
            Constant.showMessage(info.message, "操作失败");
        }
    })
}
function upperStatus(visaId){
    var url = Constant.ctx("/mulanweb/admin/visa/upperStatus");
    $.post(url, {visaId: visaId}, function (info) {
        if (info.ReturnCode == 1) {
            Constant.showMessage(info.AlertMessage, "操作成功");
            $("#datagrid").datagrid("reload");
        } else {
            Constant.showMessage(info.message, "操作失败");
        }
    })
}

//添加子签证产品
function addVisaChild(parentId, visaChildId) {
    $("#dialogDetail").dialog("move", {left: '50'});
    var url = $("#visaChildForm").attr("action");
    if (visaChildId) {
        url = Constant.ctx('/mulanweb/admin/visa/updateChild');
        $.post(Constant.ctx("/mulanweb/admin/visa/getVisaChildDetail"), {visaChildId: visaChildId}, function (visaChild) {
            $("#name").textbox('setValue', visaChild.DataList.Name);
            $("#price").numberbox('setValue', visaChild.DataList.Price);
            $("#priceOld").numberbox('setValue', visaChild.DataList.PriceOld);
            $("#visaChildId").val(visaChildId);
        });
    }
    $("#visaChild").dialog({
        title: visaChildId ? '编辑子产品' : '添加子产品',
        left:350,
        width: 300,
        height: 450,
        buttons: [
            {
                text: "保存",
                handler: function () {
                    $("#parentId").val(parentId);
                    // 保存子签证商品
                    $("#visaChildForm").form("submit", {
                        url: url,
                        onSubmit: function () {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $.messager.progress('close');	// hide progress bar while the form is invalid
                            }
                            return isValid;
                        },
                        success: function (respText) {
                            var resp = $.parseJSON(respText);
                            Constant.showMessage(resp.AlertMessage, resp.message, "操作完成");
                            if (resp.ReturnCode == 1) {
                                // $dialog.dialog("close");
                                //$("#dialogDetail").dialog("refresh");
                                refreshChilds(parentId);
                            }
                        }
                    });
                }
            },
            {
                text: "删除",
                handler: function () {
                    $.messager.confirm('警告', '您确定删除此内容?', function (r) {
                        if (r) {
                            var url = Constant.ctx("/mulanweb/admin/visa/deleteChild");
                            $.post(url,{visaChildId: visaChildId}, function (info) {
                                if (info.ReturnCode == 1) {
                                    Constant.showMessage(info.AlertMessage, "操作成功");
                                    refreshChilds(parentId);
                                    $("#visaChild").dialog('close');
                                } else {
                                    Constant.showMessage(info.message, "操作失败");
                                }
                            })
                        }
                    });

                }
            },
        ]
    });
    $("#visaChild").dialog('open').dialog('vcenter');
}

function editVisaChild(visChildId) {

}

//刷新子菜单
function refreshChilds(id) {
    $.post(Constant.ctx("/mulanweb/admin/visa/getVisaChild"), {visaId: id}, function (visaChilds) {
        var childHtml = '';
        for (var child in visaChilds.DataList) {

            childHtml = childHtml +
                '<button type="button" class="btn btn-info" style="width:25%; margin:10px" ' +
                'onclick="addVisaChild(\'' + id + '\',\'' + visaChilds.DataList[child].Id + '\')">' +
                visaChilds.DataList[child].Name + '</button>';

        }
        +'</div>';
        $("#childHtml").html(childHtml);
    })
}